import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import ArrowRightIcon from "@mui/icons-material/ArrowRight";
import ArrowLefttIcon from "@mui/icons-material/ArrowLeft";
import "./subjects.less";
import Button from "@mui/material/Button";
import Drawer from "@mui/material/Drawer";
import { switchSubjectApi, SidebarApi } from "../../api";
export default function Subjects() {
  const { actionCode } = useParams();
  const [findList, setFindList] = useState<ISubjectsItem[]>([]);
  const [sidebar, setSidebar] = useState<ISidebarItem[]>([]);
  const [isShow, setIsShow] = useState(false);
  const [actiove, setActiove] = useState(0);
  const [titles, setTitles] = useState("JAVA面试题");

  const ChangeHandle = (item: any, index: number) => {
    setActiove(index);
    setTitles(item.title);
    // 重新渲染
    switchSubjectApi(item.actionCode).then((res) => {
      setFindList(res.data);
      console.log("878787", res.data);
    });
    setIsShow(false);
  };
  // 点击打开抽屉
  const OpenShow = () => {
    setIsShow(true);
    SidebarApi().then((res) => {
      let data = sessionStorage.getItem("subjects");
      if (data) {
        setSidebar(JSON.parse(data));
      } else {
        if (res.errCode === 0) {
          // console.log(res.data);
          sessionStorage.setItem("subjects", JSON.stringify(res.data));
          setSidebar(res.data);
        }
      }
    });
  };
  const CloseShow = () => {
    setIsShow(false);
  };
  useEffect(() => {
    switchSubjectApi(actionCode).then((res) => {
      if (res.errCode === 0) {
        setFindList(res.data);
      }
    });
  }, []);

  return (
    <div className="subjects">
      <div className="top">
        <section>
          <span className="top-text">首页显示学科-Java面试题</span>
          <Button security="type">
            <span>设置默认学科</span>
            <ArrowRightIcon />
          </Button>
        </section>
        <div className="txt">
          <Button security="type" onClick={OpenShow}>
            <ArrowLefttIcon />
            <h3>{titles}</h3>
            <ArrowRightIcon />
          </Button>
          <Drawer anchor="left" open={isShow} onClose={CloseShow}>
            <ul className="list">
              {sidebar.map((item, index) => (
                <li
                  key={item.id}
                  className={actiove === index ? "actiove" : "list-li"}
                  onClick={() => ChangeHandle(item, index)}
                >
                  {item.title}
                </li>
              ))}
            </ul>
          </Drawer>
        </div>
      </div>
      <div className="bottom">
        <h3>专业科目</h3>
        <ul>
          {findList.map((item) => (
            <li key={item.id}>
              <a>{item.title}</a>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
